package com.jinyang.jetpackdemo.interceptor;

import android.content.Context;

import com.jinyang.jetpackdemo.util.NetUtil;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @Author: LiuJinYang
 * @CreateDate: 2020/5/20
 * 缓存拦截器
 */
public class CacheInterceptor implements Interceptor {


    private final Context mContext;

    public CacheInterceptor(Context mContext) {
        this.mContext = mContext;
    }

    // 有网络时 设置缓存超时时间1个小时
    int maxAge = 0;
    // 无网络时，设置超时为1个月
    int maxStale = 60 * 60 * 24 * 30;

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        if (!NetUtil.isNetworkAvailable(mContext)) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }

        Response response = chain.proceed(request);
        if (NetUtil.isNetworkAvailable(mContext)) {
            response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        } else {
            response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
        return response;
    }
}